//
//  ByUIPayVC.m
//  chequanbao_ios
//
//  Created by pro on 17/5/16.
//  Copyright © 2017年 com.itboye. All rights reserved.
//

#import "ByUIPayVC.h"

// vc
#import "ByUIPayInfoVC.h"               // 付款详情

// api
#import "ByApiShops.h"


@interface ByUIPayVC () <UITextViewDelegate>
{
    CGFloat _discountForFirst;  // 首次消费的优惠金额，如果是5元，则消费金额不低于30，10元不低于100
    CGFloat _realPay;
}

@property (nonatomic, strong) UIScrollView *scroll;
@property (nonatomic, strong) UILabel *discountLabel;
@property (nonatomic, strong) UILabel *realPayLabel;

@property (nonatomic, strong) NSMutableArray<UITextView *> *textFields;

@end

@implementation ByUIPayVC

- (void)viewDidLoad {
    [super viewDidLoad];

    self.title = @"付款";
    [self addLeftBackBarButtonItem];
    
    [self createViews];
    
    [self getPayInfo];
}

#pragma mark - 懒加载
- (UIScrollView *)scroll {
    
    if (!_scroll) {
        _scroll = [[UIScrollView alloc] initWithFrame:self.view.bounds];
        [self.view addSubview:_scroll];
    }
    return _scroll;
}
- (NSMutableArray *)textFields {
    
    if (!_textFields) {
        _textFields = [[NSMutableArray alloc] init];
    }
    return _textFields;
}

#pragma mark - 网络请求
- (void)getPayInfo {
    
    ByNetParamsModel *params = [ByNetParamsModel new];
    params.uid = BY_USER.uid;
    params.seller_id = [NSString stringWithFormat:@"%@", self.detailModel.shopsItemModel.id];
    [ByApiShops getPayInfo:params success:^(ByNetBaseResult *result) {
        
        NSDictionary *dic = result.data;
        bool isfirst = [dic[@"is_first"] boolValue];
        if (isfirst) {
            _discountForFirst = [dic[@"first_offer"] floatValue] / 100;
            if (_discountForFirst > 0) {
                NSString *need = @"";
                if (_discountForFirst == 5) {
                    need = @"满30";
                }
                if (_discountForFirst == 10) {
                    need = @"满100";
                }
                if (_discountForFirst == 20) {
                    need = @"满200";
                }
                _discountLabel.text = [NSString stringWithFormat:@"本次消费是首次消费，%@立减%.2lf元", need, _discountForFirst];
                _discountLabel.width = [_discountLabel.text getSizeOfString:14].width + 20;
                _discountLabel.x = self.scroll.width / 2;
            }
        }
    } failure:^(ByNetBaseResult *result) {
        
    }];
}

#pragma mark - 创建视图
- (void)createViews {
    
    ByModelShopsListItem *model = self.detailModel.shopsItemModel;
    
    CGFloat x, y, width, height;
    
    /*
     头视图，图标，名称，地址等
     */
    x = 0;
    y = 64;
    width = SCREEN_WIDTH;
    height = 0;  // 下面计算
    UIView *header = [[UIView alloc] initWithFrame:CGRectMake(x, y, width, height)];
    [self.scroll addSubview:header];
    
    // 图标
    x = 0;
    y = 20;
    width = 60;
    height = 60;
    UIImageView *iconView = [[UIImageView alloc] initWithFrame:CGRectMake(x, y, width, height)];
    iconView.layer.cornerRadius = height / 2;
    iconView.layer.masksToBounds = YES;
    [iconView setImageWithURL:[NSURL URLWithString:model.logo_urlstr] placeholderImage:DEFAULT_IMAGE completed:nil];
    [header addSubview:iconView];
    
    // 名称
    x = 0;
    y = 0;
    width = 0;
    height = 20;
    UILabel *nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(x, y, width, height)];
    nameLabel.adjustsFontSizeToFitWidth = YES;
    nameLabel.font = FONT(16);
    nameLabel.text = model.name;
    nameLabel.textColor = [UIColor whiteColor];
    nameLabel.textAlignment = NSTextAlignmentLeft;
    [header addSubview:nameLabel];
    
    // 地址
    x = 0;
    y = 0;
    width = 0;
    height = 0;
    UILabel *addressLabel = [[UILabel alloc] initWithFrame:CGRectMake(x, y, width, height)];
    addressLabel.numberOfLines = 2;
    addressLabel.adjustsFontSizeToFitWidth = YES;
    addressLabel.font = FONT(14);
    addressLabel.text = model.position;
    addressLabel.textColor = rgba(20, 150, 240, 1);
    addressLabel.textAlignment = NSTextAlignmentLeft;
    [header addSubview:addressLabel];
    
    // 计算位置
    // address可以多行，先计算地址是否多余一行，多余一行则使用最大宽度
    CGFloat minLeftRemain = SCREEN_WIDTH * (1.0 / 7.5);
    CGFloat margin = 10;
    CGFloat maxLabelWidth = (header.width - minLeftRemain * 2 - margin - iconView.width);
    
    if ([addressLabel.text getSizeOfString:14].width > maxLabelWidth) {
        iconView.left = minLeftRemain;
        
        nameLabel.width = maxLabelWidth;
        nameLabel.left = iconView.right + margin;

        addressLabel.width = maxLabelWidth;
        addressLabel.height = MIN([addressLabel.text getRectOfStringWithSize:CGSizeMake(maxLabelWidth, 10000) font:14].size.height , 30);
        addressLabel.left = nameLabel.left;
        
        CGFloat topRemain = (iconView.height - nameLabel.height - addressLabel.height - margin / 2) / 2;
        nameLabel.top = iconView.top + topRemain;
        addressLabel.top = nameLabel.bottom + margin / 2;
    } else {
        
        CGFloat labelWidht = MIN(MAX([nameLabel.text getSizeOfString:16].width, [addressLabel.text getSizeOfString:14].width), maxLabelWidth);
        
        CGFloat leftRemain = (header.width - labelWidht - margin - iconView.width) / 2;
        
        iconView.left = leftRemain;

        nameLabel.width = labelWidht;
        nameLabel.left = iconView.right + margin;
        
        addressLabel.width = labelWidht;
        addressLabel.height = 15;
        addressLabel.left = nameLabel.left;
        
        CGFloat topRemain = (iconView.height - nameLabel.height - addressLabel.height - margin / 2) / 2;
        nameLabel.top = iconView.top + topRemain;
        addressLabel.top = nameLabel.bottom + margin / 2;
    }
    
    header.height = header.subviews.lastObject.bottom + 20;
    // 线
    x = SCREEN_WIDTH / 15;
    y = 0;
    width = SCREEN_WIDTH / 15 * 13;
    height = 0.5;
    UIView *line = [[UIView alloc] initWithFrame:CGRectMake(x, y, width, height)];
    line.backgroundColor = [UIColor colorWithWhite:0.95 alpha:1];
    line.bottom = header.height;
    [header addSubview:line];
    
    
    /*
     输入框
     */
    x = 0;
    y = header.bottom + 30;
    width = SCREEN_WIDTH;
    height = 0;
    UIView *fieldView = [[UIView alloc] initWithFrame:CGRectMake(x, y, width, height)];
    [self.scroll addSubview:fieldView];

    NSArray *titles = @[@"消费总额：", @"不优惠金额：", @"备注："];
    margin = 15;
    for (int i = 0; i < titles.count; i ++) {
    
        width = fieldView.width * 0.55;
        height = 40;
        x = 0;
        y = (height + margin) * i;
        UITextView *tf = [[UITextView alloc] initWithFrame:CGRectMake(x, y, width, height)];
        tf.font = FONT(16);
        tf.textAlignment = NSTextAlignmentLeft;
        tf.keyboardType = UIKeyboardTypeDecimalPad;
        tf.backgroundColor = [UIColor colorWithWhite:9 alpha:1];
        [fieldView addSubview:tf];
        tf.layer.cornerRadius = 4;
        tf.right = fieldView.width * (1 - 1.0 / 12);
        // 添加输入框到全局数组中
        [self.textFields addObject:tf];
        if (i == 0) {
            tf.delegate = self;
        }
        if (i == titles.count - 1) {
            tf.height *= 2;
            tf.keyboardType = UIKeyboardTypeDefault;
        }

        x = 0;
        y = tf.top;
        width = tf.left - x;
        height = tf.height;
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(x, y, width, height)];
        label.adjustsFontSizeToFitWidth = YES;
        label.font = FONT(16);
        label.text = titles[i];
        label.textColor = [UIColor whiteColor];
        label.textAlignment = NSTextAlignmentRight;
        [fieldView addSubview:label];
        
    }
    
    fieldView.height = fieldView.subviews.lastObject.bottom;
    
    
    //
    x = 0;
    y = fieldView.bottom + 20;
    width = 0;
    height = 30;
    _discountLabel = [[UILabel alloc] initWithFrame:CGRectMake(x, y, width, height)];
    _discountLabel.adjustsFontSizeToFitWidth = YES;
    _discountLabel.font = FONT(14);
    _discountLabel.textColor = [UIColor whiteColor];
    _discountLabel.textAlignment = NSTextAlignmentCenter;
    [self.scroll addSubview:_discountLabel];
    _discountLabel.layer.borderColor = [UIColor whiteColor].CGColor;
    _discountLabel.layer.borderWidth = 1;
    
    x = self.scroll.width / 15;
    y = _discountLabel.bottom + 20;
    width = 200;
    height = 20;
    _realPayLabel = [[UILabel alloc] initWithFrame:CGRectMake(x, y, width, height)];
    _realPayLabel.adjustsFontSizeToFitWidth = YES;
    _realPayLabel.font = FONT(14);
    _realPayLabel.textColor = [UIColor whiteColor];
    _realPayLabel.textAlignment = NSTextAlignmentLeft;
    _realPayLabel.text = @"实付金额：0元";
    [self.scroll addSubview:_realPayLabel];
    
    /*
     按钮
     */
    x = _realPayLabel.left;
    y = _realPayLabel.bottom;
    width = self.scroll.width - x * 2;
    height = 40;
    UIButton *payButton = [UIButton buttonWithType:UIButtonTypeCustom];
    payButton.backgroundColor = rgba(20, 150, 240, 1);
    [payButton setFrame:CGRectMake(x, y, width, height)];
    [payButton setTitle:@"付款" forState:UIControlStateNormal];
    [payButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [payButton addTarget:self action:@selector(pay) forControlEvents:UIControlEventTouchUpInside];
    payButton.layer.cornerRadius = 8;
    [self.scroll addSubview:payButton];
    
    
    
    /*
     计算scroll的滑动
     */
    self.scroll.contentSize = CGSizeMake(0, self.scroll.subviews.lastObject.bottom + 20);
}


#pragma mark - textView delegate
- (void)textViewDidEndEditing:(UITextView *)textView {
    
    if (_discountForFirst == 5) {
        if (self.textFields[0].text.floatValue < 30) {
            _realPay = textView.text.floatValue;
        } else {
            _realPay = textView.text.floatValue - _discountForFirst;
        }
    }
    else if (_discountForFirst == 10) {
        if (self.textFields[0].text.floatValue < 100) {
            _realPay = textView.text.floatValue;
        } else {
            _realPay = textView.text.floatValue - _discountForFirst;
        }
    }else if (_discountForFirst == 20){
        if (self.textFields[0].text.floatValue < 200) {
            _realPay = textView.text.floatValue;
        } else {
            _realPay = textView.text.floatValue - _discountForFirst;
        }

    }
    else{
        _realPay = textView.text.floatValue;
    }
    _realPayLabel.text = [NSString stringWithFormat:@"实付金额：%.2lf", _realPay];
}


#pragma mark - 点击
- (void)pay {
    
    if (self.textFields[0].text.length == 0 || self.textFields[0].text.floatValue == 0) {
        [ByCoreToolAlert showFailureWithText:@"请填写正确的消费总额"];
        return;
    }
    
//    if (_discountForFirst == 5) {
//        if (self.textFields[0].text.floatValue < 30) {
//            [ByCoreToolAlert showFailureWithText:@"本次消费金额不能少于30"];
//            return;
//        }
//    }
//    if (_discountForFirst == 10) {
//        if (self.textFields[0].text.floatValue < 100) {
//            [ByCoreToolAlert showFailureWithText:@"本次消费金额不能少于100"];
//            return;
//        }
//    }
    
    
    ByNetParamsModel *params = [ByNetParamsModel new];
    params.uid = BY_USER.uid;
    params.seller_id = [NSString stringWithFormat:@"%@", self.detailModel.shopsItemModel.id];
    params.amount = [NSString stringWithFormat:@"%.2lf", self.textFields[0].text.floatValue * 100];
    if (self.textFields[1].text.length == 0) {
        params.no_discount = @"0";
    } else {
        params.no_discount = [NSString stringWithFormat:@"%.2lf", self.textFields[1].text.floatValue * 100];
    }
    if (self.textFields[2].text.length != 0) {
        params.note = self.textFields[2].text;
    }
    [ByCoreToolAlert showLoadind:@"正在生成订单"];
    [ByApiShops getPayOrder:params success:^(ByNetBaseResult *result) {
                
        ByUIPayInfoVC *vc = [[ByUIPayInfoVC alloc] init];
        vc.orderModel = result.data;
        vc.name = self.detailModel.shopsItemModel.name;
//        vc.payMoney = [NSString stringWithFormat:@"%.2lf", _realPay];
//        vc.notDiscountMoney = self.textFields[1].text;
//        vc.notes = self.textFields[2].text;
        vc.store_id = self.detailModel.shopsItemModel.id;
        [self by_normalPush:vc hasNavi:YES];
        
    } failure:^(ByNetBaseResult *result) {
        
        [ByCoreToolAlert showFailureWithText:result.msg];
    }];
    
   
}


@end
